/*
 * @Author: WangLi
 * @Date: 2024-04-04 17:38:31
 * @LastEditors: WangLi
 * @LastEditTime: 2024-05-19 07:28:58
 */
export const CODE_MESSAGE = {
  10000: "服务器成未初始化蓝牙适配器功返回请求的数据。",
  10001: "当前蓝牙适配器不可用",
  10002: "没有找到指定设备",
  10003: "连接失败",
  10004: "没有找到指定服务",
  10005: "没有找到指定特征",
  10006: "当前连接已断开",
  10007: "当前特征不支持此操作",
  10008: "其余所有系统上报的异常",
  10009: "Android 系统特有，系统版本低于 4.3 不支持 BLE",
  10012: "连接超时",
  10013: "连接 deviceId 为空或者是格式不正确",
};
export function stringToUint8Array(str) {
	if(typeof str === 'number'){
		console.log('number类型:',str);
		let buffer = new ArrayBuffer(2); // 创建一个1字节的ArrayBuffer
		let dataView = new DataView(buffer);
		dataView.setUint16(0, str, true);
		return buffer
	}else{
		var arr = [];
		for (var i = 0, j = str.length; i < j; ++i) {
		  arr.push(str.charCodeAt(i));
		}
		var tmpUint8Array = new Uint8Array(arr);
		return tmpUint8Array.buffer;
	}
}
// ArrayBuffer转16进度字符串示例
export function ab2hex(value) {
  // var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
  //   return ("00" + bit.toString(16)).slice(-2);
  // });
  // return hexArr.join("");
  let buffer = new ArrayBuffer(16);
  let dataView = new DataView(buffer);
  dataView.setUint8(0, value);

  return buffer;
}
/**
 * @description: 向蓝牙低功耗设备特征值中写入16进制数据
 * @param {*} serviceId 蓝牙特征对应服务的 UUID
 * @param {*} characteristicId 蓝牙特征的 UUID
 * @param {*} buffer 蓝牙设备特征对应的二进制值
 * @param {*} msg 提示消息内容
 * @param {*} cb 回调函数
 */
export function writeBLECharacteristicValue(serviceId, characteristicId, buffer, msg, cb) {
  const app = getApp();
  const { deviceId } = app.globalData;
  const params = { deviceId, serviceId, characteristicId, value: stringToUint8Array(buffer)};
  console.log("writeBLECharacteristicValue", params);
  uni.writeBLECharacteristicValue({
    ...params,
    success(res) {
      console.log("writeBLECharacteristicValue success", res);
      if (msg) {
        uni.showToast({
          title: `${msg}成功`,
          icon: "none",
        });
      } else if (cb) {
        cb({ code: 200 });
      }
    },
    fail(res) {
      console.log("writeBLECharacteristicValue fail", res);
      const errorMsg = CODE_MESSAGE[res.errCode];
      if (msg) {
        uni.showToast({
          title: `${msg}失败：${errorMsg}`,
          icon: "none",
          duration: 2000,
        });
      } else if (cb) {
        cb({ code: 500 });
      }
    },
  });
}

/**
 * @description: 向蓝牙低功耗设备特征值中写入16进制数据
 * @param {*} deviceId 蓝牙设备 id
 * @param {*} serviceId 蓝牙特征对应服务的 UUID
 * @param {*} characteristicId 蓝牙特征的 UUID
 * @param {*} buffer 蓝牙设备特征对应的二进制值
 * @param {*} msg 提示消息内容
 * @param {*} cb 回调函数
 */
export function writeBLECharacteristicValueByDevice(deviceId, serviceId, characteristicId, buffer, msg, cb) {
  const params = { deviceId, serviceId, characteristicId, value: stringToUint8Array(buffer)};
  console.log("writeBLECharacteristicValue", params);
  uni.writeBLECharacteristicValue({
    ...params,
    success(res) {
      console.log("writeBLECharacteristicValue success", res);
      if (msg) {
        uni.showToast({
          title: `${msg}成功`,
          icon: "none",
        });
      } else if (cb) {
        cb({ code: 200 });
      }
    },
    fail(res) {
      console.log("writeBLECharacteristicValue fail", res);
      const errorMsg = CODE_MESSAGE[res.errCode];
      if (msg) {
        uni.showToast({
          title: `${msg}失败：${errorMsg}`,
          icon: "none",
          duration: 2000,
        });
      } else if (cb) {
        cb({ code: 500 });
      }
    },
  });
}

export function getUuid(uuid) {
  const key = `6e40${uuid}-b5a3-f393-e0a9-e50e24dcca9e`;
  return key;
}
